package com.health.fragment.jtys;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.health.AddCustomer;
import com.health.AddCustomerActivity;
import com.health.MainActivity_Menu_JTYS;
import com.health.MainActivity_Menu_Tj;
import com.health.NovaApplication;
import com.health.R;
import com.health.adapter.JTYSDAAdapter;
import com.health.db.DbManager;
import com.health.db.FDbManager;
import com.health.dialog.NewArchivesDialog;
import com.health.fragment.Main_tj_loginFragment2;
import com.health.fragment.NovaFragment;
import com.health.model.PageData;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tools.DeleteDAData;
import com.health.tools.SPUtil;
import com.health.widget.CommomDialog;
import com.health.widget.EditTextWithDate;
import com.zkteco.id300.IDCardReader;
import com.zkteco.id300.meta.IDCardInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.novabluetooth.services.ktxyj.Constants.DEFAULT_IDCARD;

/**
 * 居民管理
 *
 * @author nova
 */
public class JTYSDA extends NovaFragment implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.et_customer_idcard)
    EditText etCustomerIdcard;
    @BindView(R.id.et_customer_name)
    EditText etCustomerName;
    @BindView(R.id.tv_query_read_idcard)
    TextView tvQueryReadIdcard;
    @BindView(R.id.exam_starttime)
    EditTextWithDate examStarttime;
    @BindView(R.id.exam_endtime)
    EditTextWithDate examEndtime;
    @BindView(R.id.tv_query)
    TextView tvQuery;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.rel_query)
    RelativeLayout relQuery;
    @BindView(R.id.et_content_search)
    EditText etContentSearch;
    @BindView(R.id.ib_search)
    ImageButton ibSearch;
    @BindView(R.id.ib_select)
    ImageButton ibSelect;
    @BindView(R.id.rb_all)
    RadioButton rbAll;
    @BindView(R.id.rb_checked)
    RadioButton rbChecked;
    @BindView(R.id.rb_unchecked)
    RadioButton rbUnchecked;
    @BindView(R.id.rg)
    RadioGroup rg;
    @BindView(R.id.linear_head)
    LinearLayout linearHead;
    @BindView(R.id.gd_da)
    GridView gdDa;
    @BindView(R.id.tv_allpage)
    TextView tvAllpage;
    @BindView(R.id.tv_cupage)
    TextView tvCupage;
    @BindView(R.id.btn_top)
    Button btnTop;
    @BindView(R.id.btn_next)
    Button btnNext;
    private View docDAView = null;
    /**
     * 身份证读卡器相关
     **/
    IDCardReader idCardReader = null;
    BluetoothAdapter mBluetoothAdapter;// ble
    BluetoothManager mBluetoothManager;
    boolean mbStop = true;
    private WorkThread workThread = null;

    public final static String TYPE_ALL = "all";
    public final static String TYPE_SIGN = "sign";
    public final static String TYPE_UNSIGN = "unsign";
    private static String typeSignContent = "";// 类型

    private int pagesize = 9;
    private int pageall = 1;
    private PageData nd;
    private JTYSDAAdapter jtysDAAdapter = null;
    private ARCHIVE_BASEINFO userinfo = null;
    private String str_jdrno = "";//建档人no
    private String strIdcard = "";//建档人身份证号
    private List<ARCHIVE_BASEINFO> infos = new ArrayList<>();

    @Override
    public View findViews(LayoutInflater inflater) {
        userinfo = NovaApplication.getUserInfo();
        docDAView = inflater.inflate(R.layout.jtys_da, null);
        ButterKnife.bind(this, docDAView);

        str_jdrno = SPUtil.getStr_jdrno(getActivity());
        pagesize = NovaApplication.dbManger.pagesize;

        initBlooth();
        typeSignContent = TYPE_ALL;
        return docDAView;
    }

    @Override
    public void setupView(View view) {

    }

    @Override
    public void addListener() {
    }

    @Override
    public void setData() {
    }

    private void setDatasByType(String typeSign) {
        if (infos == null) {
            infos = new ArrayList<>();
        }
        nd = new PageData();
        nd.setCountall(pageall);
        nd.setCountcurrent(1);

        typeSignContent = typeSign;
        String startTime = examStarttime.getText().toString().trim();
        String endTime = examEndtime.getText().toString().trim();
        String str_realname = etCustomerName.getText().toString().trim();
        String str_id_card = etCustomerIdcard.getText().toString().trim();

        int count = 0;
        if (TYPE_ALL.equals(typeSign)) {
            count = NovaApplication.dbManger.getCustomerCount(str_jdrno, startTime, endTime, str_realname, str_id_card);
        } else if (TYPE_SIGN.equals(typeSign)) {
            count = NovaApplication.dbManger.getCountByJDRSign(str_jdrno, str_jdrno, etCustomerName.getText().toString().trim());
        } else if (TYPE_UNSIGN.equals(typeSign)) {
            count = NovaApplication.dbManger.getCountByJDRUnSign(str_jdrno, str_jdrno, etCustomerName.getText().toString().trim());
        }

        Log.w("eeeeeeeeeeepagcount", "" + count);
        if (count > 0) {

            pageall = count % pagesize == 0 ? count / pagesize : count / pagesize + 1;
            nd.setCountall(pageall);
            nd.setCountcurrent(1);
            getPageData(typeSign, 1);
        } else {
            nd = new PageData();
            // nd.setCurrentPage("1");
            nd.setCountall(pageall);
            nd.setCountcurrent(1);
            tvAllpage.setText("");
            tvCupage.setText("");
            gdDa.setAdapter(null);
        }

        gdDa.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                userinfo = infos.get(position);
                NovaApplication.setUserInfo(userinfo);
                SPUtil.setstr_idCard(getContext(), userinfo.getIDCARD());
                if (userinfo != null) {
                    Log.e("档案点击事件！！！", userinfo.getCUSTOMERNAME() + "\n" + userinfo.getIDCARD());
                    Intent intent = new Intent(getActivity(), MainActivity_Menu_Tj.class);
                    getActivity().startActivity(intent);
                }
            }
        });
        gdDa.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                // IS_UPDATE //Y 未上传 N已上传
                if ("Y".equals(infos.get(position).getIS_UPDATE())) {
                    showDeleteDialog(position);
                }
                return true;
            }
        });
    }

    /**
     * 初始化蓝牙信息
     *
     * @author 王婷婷
     * @date 2015年12月18日 上午10:41:48
     */
    @SuppressLint("LongLogTag")
    private void initBlooth() {
        System.out.println("00000000000000000");
        if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Log.w("noticeservice-----------111----", "手机不支持BLE");
        }

        mBluetoothManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        // mBluetoothAdapter2 = BluetoothAdapter.getDefaultAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Log.w("noticeservice-----------222----", "手机不支持蓝牙");
        }
        Log.w("noticeservice-----------tt----", "手机支持蓝牙");
        // 开启蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            boolean flag = mBluetoothAdapter.enable();
            // 开启蓝牙成功还是失败
            if (flag) {
                NovaApplication.isBluetoothOpen = true;
            } else {
                NovaApplication.isBluetoothOpen = false;
            }

        } else {
            NovaApplication.isBluetoothOpen = true;
        }
    }

    /**
     * 获取分页数据
     *
     * @param type
     * @author 王婷婷
     * @date 2018年1月16日 下午7:08:17
     */
    private void getPageData(String type, int currentPage) {

        String startTime = examStarttime.getText().toString().trim();
        String endTime = examEndtime.getText().toString().trim();
        String str_realname = etCustomerName.getText().toString().trim();
        String str_id_card = etCustomerIdcard.getText().toString().trim();
        tvAllpage.setText("总页数：" + pageall);
        tvCupage.setText("当前页：" + currentPage);
        Log.w("eeeeeeeeeeepageall", "" + pageall);
        if (TYPE_ALL.equals(type)) {
            infos = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectUserByQYSignPage(startTime, endTime, str_jdrno, str_realname, currentPage,
                    DbManager.TYPE_ALL, str_id_card);
        } else if (TYPE_SIGN.equals(type)) {
            infos = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectUserByQYSignPage(startTime, endTime, str_jdrno, str_realname, currentPage,
                    DbManager.TYPE_SIGN, str_id_card);
        } else if (TYPE_UNSIGN.equals(type)) {
            infos = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectUserByQYSignPage(startTime, endTime, str_jdrno, str_realname, currentPage,
                    DbManager.TYPE_UNSIGN, str_id_card);
        }
        for (ARCHIVE_BASEINFO info:infos) {
            if (DEFAULT_IDCARD.equals(info.getIDCARD())){
                infos.remove(info);
            }
        }
        jtysDAAdapter = new JTYSDAAdapter(getActivity(), infos, type, gdDa);
        gdDa.setAdapter(jtysDAAdapter);
        jtysDAAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            setDatasByType(typeSignContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.iv_add, R.id.tv_query, R.id.tv_query_read_idcard, R.id.btn_top, R.id.btn_next, R.id.ib_search, R.id.ib_select})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_query://查询
                setDatasByType(typeSignContent);
                break;
            case R.id.ib_search://旧搜索
                setDatasByType(typeSignContent);
                break;
           /* case R.id.ib_select:// 筛选按钮
                Log.e("tag", searchContent + "-------------content_search");
                setDatasByType(typeSignContent);
                break;*/
            case R.id.iv_add://新建档案
                startActivity(new Intent(getActivity(), AddCustomerActivity.class));
                break;
            case R.id.tv_query_read_idcard://身份证读卡
                connect();
                break;
            case R.id.btn_top:
                preData();
                break;
            case R.id.btn_next:
                nextData();
                break;
        }
    }

    //connect和disconnect都是hide方法，普通应用只能通过反射机制来调用该方法
    private void connect() {
        try {
            if (idCardReader != null) {
                idCardReader.closeDevice();
            } else {
                idCardReader = new IDCardReader();
                if (mBluetoothAdapter != null) {
                    Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
                    for (BluetoothDevice device : devices) {
                        if (device.getName().contains("ID300")) {
                            idCardReader.setDevice(device.getAddress());
                        }
                    }
                }

            }
        } catch (Exception e) {
            showTextDialog("请检查设备是否运行正常");
            idCardReader = null;
            return;
        }

        int i = idCardReader.openDevice();
        Log.e("555555555", i + "");
        if (i == 0) {
            showTextDialog("读卡器连接成功");
            mbStop = false;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //新建一个Message对象，存储需要发送的消息
                    Message message = new Message();
                    message.what = 1;
                    //然后将消息发送出去
                    handler.sendMessage(message);
                }
            }).start();
           /* workThread = new WorkThread();
            workThread.start();// 线程启动*/
        }

    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (!ReadCardInfo()) {
                        Log.e("**********", "请放卡...");
                    } else {
                        Log.e("**********", "读卡成功，请放入下一张卡");
                    }
                    break;
                default:
                    break;
            }
        }
    };
    private int readNum;

    private class WorkThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (!mbStop) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {

                        if (!ReadCardInfo()) {
                            if (readNum == 10) {
                                readNum = 0;
                                interrupt();
                            }
                            readNum++;
                            Log.e("**********", "请放卡...");
                        } else {
                            workThread.interrupt();
                            Log.e("**********", "读卡成功，请放入下一张卡");
                        }
                    }
                });

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    private boolean ReadCardInfo() {
        try {
            if (!idCardReader.sdtFindCard() || !idCardReader.sdtSelectCard()) {
                return false;
            }
            showTextDialog("正在读卡");
            final IDCardInfo idCardInfo = new IDCardInfo();
            if (idCardReader.sdtReadCard(1, idCardInfo)) {
                etCustomerIdcard.setText(idCardInfo.getId());
                etCustomerName.setText(idCardInfo.getName());
                return true;
            } else {
                //playSound(9, 0);
            }
            showTextDialog("读卡失败，请重试");
            return false;
        } catch (Exception e) {
            showTextDialog("读卡失败，请检查设备是否运行正常");
            return false;
        }
    }

    public void preData() {
        // 上一页
        if (nd.getCountcurrent() > nd.getCountall()) {
            nd.setCountcurrent(nd.getCountall());
        }

        if (nd.getCountcurrent() == 1) {
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("已经是第一页了");
            btnTop.setBackground(getResources().getDrawable(R.drawable.btn_top2));
        } else {
            nd.setCountcurrent(nd.getCountcurrent() - 1);
            infos = new ArrayList<>();
            gdDa.setAdapter(null);
            getPageData(typeSignContent, nd.getCountcurrent());
        }
        setButtonBg();
    }

    public void nextData() {

        if (nd.getCountcurrent() > nd.getCountall()) {
            nd.setCountcurrent(nd.getCountall());
        }

        if (nd.getCountcurrent() == nd.getCountall()) {
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("已经是最后一页了");
            btnNext.setBackground(getResources().getDrawable(R.drawable.btn_bottom2));
        } else {
            nd.setCountcurrent(nd.getCountcurrent() + 1);
            infos = new ArrayList<>();
            gdDa.setAdapter(null);
            getPageData(typeSignContent, nd.getCountcurrent());
        }

        setButtonBg();
    }

    /**
     * 设置背景色
     *
     * @author 王婷婷
     * @date 2016年2月22日 上午11:21:24
     */
    @SuppressLint("NewApi")
    private void setButtonBg() {
        if (nd.getCountcurrent() == 1) {
            btnTop.setBackground(getResources().getDrawable(R.drawable.btn_top2));
            btnNext.setBackground(getResources().getDrawable(R.drawable.btn_bottom1));
        } else if (nd.getCountcurrent() == nd.getCountall()) {
            btnTop.setBackground(getResources().getDrawable(R.drawable.btn_top1));
            btnNext.setBackground(getResources().getDrawable(R.drawable.btn_bottom2));
        } else if ((nd.getCountcurrent() > 1) && (nd.getCountcurrent() < nd.getCountall())) {
            btnTop.setBackground(getResources().getDrawable(R.drawable.btn_top1));
            btnNext.setBackground(getResources().getDrawable(R.drawable.btn_bottom1));
        }
    }

    private PopupWindow popWindow;
    private Button bt_clear;
    private Button bt_search;

    private CheckBox people1;
    private CheckBox people2;
    private CheckBox people3;
    private CheckBox people4;
    private CheckBox people5;
    private CheckBox people6;
    private CheckBox people7;
    private CheckBox people8;
    private CheckBox people9;
    private CheckBox people10;
    private int age;
    private List<CheckBox> peopleGroupChecks = new ArrayList<CheckBox>();

    private RadioButton detail_state_yqy;
    private RadioButton detail_state_wqy;
    private RadioGroup rg_state_qy;

    private CheckBox detail_state_xsf;
    private CheckBox detail_state_ysf;

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (people1.isChecked()) {
            for (int i = 1; i < peopleGroupChecks.size(); i++) {
                peopleGroupChecks.get(i).setChecked(false);
            }
        }

        if (detail_state_ysf.isChecked()) {
            detail_state_xsf.setChecked(false);
        }
        if (detail_state_xsf.isChecked()) {
            detail_state_ysf.setChecked(false);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            if (idCardReader != null) {
                idCardReader.closeDevice();
            }
        } catch (Exception e) {

        }
    }

    /**
     * 显示删除档案对话框
     *
     * @param position
     * @author 王婷婷
     * @date 2017年12月18日 下午5:31:27
     */
    private void showDeleteDialog(final int position) {
        new CommomDialog(getActivity(), R.style.dialog, "", new CommomDialog.OnCloseListener() {

            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    DeleteDAData.deleteDaData(infos.get(position).getIDCARD());
                    setDatasByType(JTYSDA.typeSignContent);
                    dialog.dismiss();
                }

            }

        }).setTitle("是否删除档案").setPositiveButton("删除").setNegativeButton("取消").show();
    }

}
